package com.hfut.wxy.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.hfut.wxy.common.Constants;
import com.hfut.wxy.common.OkHttp;
import com.hfut.wxy.common.exception.WxyException;
import com.hfut.wxy.common.interceptor.TokenInterceptor;
import com.hfut.wxy.common.parent.ParentService;
import com.hfut.wxy.common.utils.JwtUtil;
import com.hfut.wxy.entity.mysql.WxyUserInfo;
import com.hfut.wxy.service.ISignService;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Base64Utils;
import org.springframework.util.DigestUtils;
import sun.misc.BASE64Encoder;

import java.io.File;
import java.io.FileInputStream;
import java.net.URLEncoder;


@Service
@Transactional(rollbackFor = Exception.class)
public class SignServiceImpl extends ParentService implements ISignService  {
    @Autowired
    private OkHttp okHttp;

    @Override
    public Object login(String code) {
        JSONObject jsonObject = okHttp.getOpenId(code);
        if (jsonObject == null){
            throw WxyException.of("code异常");
        }
        String openId = jsonObject.getString("openid");
        WxyUserInfo wxyUserInfo = userDao.findAllByOpenid(openId);
        if (wxyUserInfo == null || wxyUserInfo.getId() == null){
            wxyUserInfo = new WxyUserInfo();
            wxyUserInfo.setOpenid(openId);
            // TODO: 2020/5/16 添加学校id
            wxyUserInfo.setSchoolId(1);
            wxyUserInfo = userDao.save(wxyUserInfo);
        }
        String session_key  = jsonObject.getString("session_key");
        String token = JwtUtil.generateToken(wxyUserInfo.getId(), session_key);
        redisUtil.set(TokenInterceptor.TOKEN+wxyUserInfo.getId(),session_key,TokenInterceptor.EXPIRED_TIME);
        JSONObject re = new JSONObject();
        re.put("id",wxyUserInfo.getId());
        re.put("token",token);
        return re;
    }

    @Override
    @SuppressWarnings("all")
    public boolean verify(Integer id, String userName, String passWord, String phone) throws Exception{
        if (userName.equals("2020010101")){
            WxyUserInfo wxyUserInfo = userDao.getById(id);
            if (wxyUserInfo == null){
                wxyUserInfo = new WxyUserInfo();
                wxyUserInfo.setId(id);
            }
            wxyUserInfo.setPhone(phone);
            wxyUserInfo.setUsername("2020010101");
            wxyUserInfo.setPassword("2020010101");
            wxyUserInfo.setYear(2020);
            wxyUserInfo.setMajor("测试用户专业");
            wxyUserInfo.setName("测试用户姓名");
            wxyUserInfo = userDao.save(wxyUserInfo);
        }
        System.setProperty("webdriver.chrome.driver","/opt/chromedriver");
        ChromeOptions chromeOptions = new ChromeOptions();
        chromeOptions.addArguments("--no-sandbox");
        chromeOptions.addArguments("--disable-dev-shm-usage");
        chromeOptions.addArguments("--headless");
        chromeOptions.addArguments("--disable-gpu");
        ChromeDriver driver = new ChromeDriver(chromeOptions);
       try {
           final String URL = "http://my.hfut.edu.cn/";
           driver.get(URL);
           System.out.println(driver.getTitle());
           WebElement element = driver.findElementById("captchaImg");
           File file = element.getScreenshotAs(OutputType.FILE);
//        FileUtils.copyFile(file,new File("imgs/img2.png"));
           FileInputStream fis = new FileInputStream(file);
           byte[] bytes = new byte[fis.available()];
           int i = fis.read(bytes);
           fis.close();
           String res = Base64Utils.encodeToString(bytes);
           res = URLEncoder.encode(res, "UTF-8");
           JSONObject jsonObject = okHttp.getVCode(Constants.access_token,res);
           String vCode = jsonObject.getJSONArray("words_result").getJSONObject(0).getString("words").trim();
           System.out.println(vCode);
           driver.findElementById("username").sendKeys(userName);
           driver.findElementById("password").sendKeys(passWord);
           driver.findElementById("code").sendKeys(vCode);
           driver.findElementByName("btn").submit();
           Thread.sleep(5000);//等待登录
           String cUrl = driver.getCurrentUrl();
           System.out.println(cUrl);
           final String infoUrl = "http://my.hfut.edu.cn/index.portal?.pn=p383_p506";
           driver.get(infoUrl);
           Document document = Jsoup.parse(driver.getPageSource());
           Elements tds = document.select("#pf416 > div > div.portletContent > table > tbody > tr.portlet-table-odd.portlet-table-down.portlet-table-even > td");
           if (tds.size() == 0){
               return false;
           }
           WxyUserInfo wxyUserInfo = userDao.getById(id);
           if (wxyUserInfo == null){
               wxyUserInfo = new WxyUserInfo();
               wxyUserInfo.setId(id);
           }
           wxyUserInfo.setPhone(phone);
           wxyUserInfo.setUsername(userName);
           wxyUserInfo.setPassword(DigestUtils.md5DigestAsHex(passWord.getBytes()));
           wxyUserInfo.setYear(Integer.valueOf(tds.get(10).text()));
           wxyUserInfo.setMajor(tds.get(8).text()+"-"+tds.get(9).text());
           wxyUserInfo.setName(tds.get(1).text());
           wxyUserInfo = userDao.save(wxyUserInfo);
       } catch (Exception e){
           e.printStackTrace();
           return false;
       } finally {
           driver.close();
       }

        return true;
    }

    @Override
    public WxyUserInfo getUserInfo(Integer id) {
        return userDao.getById(id);
    }
}
